import {Component, ReactElement} from 'react';
import React from 'react';
import ProTable, {ProColumns} from '@ant-design/pro-table';
import {Divider, Switch, Popconfirm} from 'antd';
import CreateForm from '@/pages/ListTableList/components/CreateForm';
import UpdateForm from '@/pages/ListTableList/components/UpdateForm';
import {FormInstance} from 'antd/lib/form';
// @ts-ignore
import {ToolBarProps} from '@ant-design/pro-table/lib/component/toolBar';
import {newGuid} from "@/utils/utils";


interface HighPerformTableProps<T> {
  columns: Array<ProColumns<T>>;
  additionOptions?: Array<{ title: string; onClick: (record: any) => any }>;
  toolBarRender?: ToolBarProps<T>['toolBarRender'] | false;
  rowKey?: string;
  handleAdd?: (item: T) => Promise<boolean>;
  handleDelete?: (id: number) => Promise<boolean>;
  handleUpdate?: (item: T) => Promise<boolean>;
  handleChangeState?: (data: any, state: boolean) => Promise<boolean>;
  onClickUpdate?: (record: any) => any;
  requestGetData?: any;
  hideOptions?: boolean;
  overrideState?: (record: any) => ReactElement;
  /* 不开启状态和操作 */
  action?: boolean;
  hidePagination?: boolean;

  // requestGetData?: (
  //   params: {
  //     pageSize?: number;
  //     current?: number;
  //   },
  //   sort: {
  //     [key: string]: 'ascend' | 'descend';
  //   },
  //   filter: {
  //     [key: string]: React.ReactText[];
  //   },
  // ) => Promise<RequestData<T>>;
}

interface HighPerformTableState<T> {
  selectedRowsState: Array<T>;
  createModalVisible: boolean;
  updateModalVisible: boolean;
  currentSelect: any;
}

/**
 * 自定义高级列表
 */
class HighPerformTable<T> extends Component<HighPerformTableProps<T>, HighPerformTableState<T>> {
  actionRef: any;

  constructor(props: HighPerformTableProps<T>) {
    super(props);
    this.state = {
      selectedRowsState: [],
      createModalVisible: false,
      updateModalVisible: false,
      currentSelect: {},
    };
  }

  componentDidMount() {
  }

  /**
   * 显示新建弹窗
   * @param value
   */
  handleModalVisible(value: boolean) {
    this.setState({createModalVisible: value});
  }

  /**
   * 显示修改弹窗
   * @param value
   */
  handleUpdateModalVisible(value: boolean, record: any) {
    this.setState({updateModalVisible: value, currentSelect: record});
  }

  /**
   * 修改表单数据
   * @param value
   */
  handleUpdateCurrent(record: any) {
    this.setState({currentSelect: record});
  }

  /*获取表单信息*/
  getCurrentSelect() {
    return this.state.currentSelect;
  }

  reload() {
    this.actionRef?.reload();
  }

  render() {
    const columns: any = this.props.action ?
      [...this.props.columns]
      : [
        ...this.props.columns,
        {
          title: '状态',
          dataIndex: 'state',
          valueType: 'state',
          hideInForm: true,
          render: (_: any, record: any) =>
            this.props.overrideState ? (
              this.props.overrideState(record)
            ) : (
              <>
                {this.props.handleChangeState ? (
                  <Switch
                    defaultChecked={record.state}
                    checked={record.state}
                    onChange={async (state) => {
                      await this.props.handleChangeState?.(record, state);
                      this.actionRef.reload();
                    }}
                  />
                ) : record.state === 1 ? (
                  '启用中'
                ) : (
                  '禁用中'
                )}
              </>
            ),
        },
      ];
    if (!this.props.hideOptions && !this.props.action) {
      columns.push({
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_: any, record: any) => (
          <div>
            <div style={{display: 'inline-block', flexDirection: 'row'}}>
              {this.props.additionOptions?.map((item, index) => (
                <div key={newGuid()}>
                  <a onClick={() => item.onClick(record)}>{item.title}</a>
                  {index < (this.props.additionOptions.length) && (this.props.handleUpdate || this.props.onClickUpdate || this.props.handleDelete) &&
                  <Divider type="vertical" key={index}/>}
                </div>
              ))}
            </div>
            {(this.props.handleUpdate || this.props.onClickUpdate) && (
              <span>
                <a
                  onClick={() => {
                    this.setState({currentSelect: record});
                    if (!this.props.onClickUpdate) this.handleUpdateModalVisible(true, record);
                    this.props.onClickUpdate?.(record);
                  }}
                >
                  修改
                </a>
                <Divider type="vertical"/>
              </span>
            )}
            {this.props.handleDelete && (
              <>

                <Popconfirm
                  title="确定要删除该条记录?"
                  okText="确定"
                  onConfirm={() => {
                    this.props.handleDelete?.(record.id || record).then((success) => {
                      if (success) this.actionRef.reload();
                    });
                  }}
                  cancelText="取消"
                >
                  <a href="#">删除</a>
                </Popconfirm>
              </>
            )}
          </div>
        ),
      });
    }
    var config = this.props.hidePagination ? {pagination: false} : {}
    return (
      <div>
        <ProTable<T>
          {...config}
          headerTitle={null}
          actionRef={(ref) => (this.actionRef = ref)}
          rowKey={this.props.rowKey || 'id'}
          toolBarRender={this.props.toolBarRender}
          search={false}
          options={false}
          request={this.props.requestGetData}
          columns={columns}
          rowSelection={false}
        />
        <CreateForm
          onCancel={() => this.handleModalVisible(false)}
          modalVisible={this.state.createModalVisible}
        >
          <ProTable<T, T>
            onSubmit={async (value) => {
              const success = await this.props.handleAdd?.(value);
              if (success) {
                this.handleModalVisible(false);
                if (this.actionRef) {
                  this.actionRef.reload();
                }
              }
            }}
            type="form"
            columns={columns}
            rowSelection={{}}
          />
        </CreateForm>
        <UpdateForm
          modalVisible={this.state.updateModalVisible}
          onCancel={() => {
            this.handleUpdateModalVisible(false, null);
          }}
        >
          <ProTable<T, T>
            onSubmit={async (value) => {
              const success = await this.props.handleUpdate?.({
                ...this.state.currentSelect,
                ...value,
              });
              if (success) {
                this.handleUpdateModalVisible(false, null);
                if (this.actionRef) {
                  this.actionRef.reload();
                }
              }
            }}
            type="form"
            formRef={(ref: FormInstance) => {
              ref?.setFieldsValue(this.state.currentSelect);
            }}
            columns={columns}
            rowSelection={{}}
          />
        </UpdateForm>
      </div>
    );
  }
}

export default HighPerformTable;
